package com.sluggard.common.adapter;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.lang.reflect.Type;

public class GrantedAuthorityTypeAdapter implements JsonSerializer<GrantedAuthority>, JsonDeserializer<GrantedAuthority> {
    @Override
    public GrantedAuthority deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        return new SimpleGrantedAuthority(jsonElement.getAsString());
    }

    @Override
    public JsonElement serialize(GrantedAuthority grantedAuthority, Type type, JsonSerializationContext jsonSerializationContext) {
        return new JsonPrimitive(grantedAuthority.getAuthority());
    }
}
